package com.wgts.wgts.mvp.view.activity.mycenter;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseActivity;
import com.wgts.wgts.control.oss.FileUtils;
import com.wgts.wgts.control.oss.OssService;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerIdeaBackActivityComponent;
import com.wgts.wgts.dagger.module.IdeaBackActivityModule;
import com.wgts.wgts.mvp.presenter.IIdeaBackActivityPresenter;
import com.wgts.wgts.mvp.view.IIdeaBackActivityView;
import com.wgts.wgts.netmodle.req.IdeaBackRequest;
import com.wgts.wgts.netmodle.resp.IdeaBackEntity;
import com.google.gson.Gson;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/*
 *
 *
 *   data:2018/9/2817:10
 *
 */
@RuntimePermissions
public class IdeaBackActivity extends BaseActivity implements IIdeaBackActivityView{
    @BindView(R.id.back_btn_image)
    ImageView backBtnImage;
    @BindView(R.id.back_btn_ly)
    LinearLayout backBtnLy;
    @BindView(R.id.include_title)
    TextView includeTitle;
    @BindView(R.id.include_text)
    TextView includeText;
    @BindView(R.id.include_right_image)
    ImageView includeRightImage;
    @BindView(R.id.include_right_ly)
    LinearLayout includeRightLy;
    @BindView(R.id.email_address)
    EditText emailAddress;
    @BindView(R.id.idea_back_detail)
    EditText ideaBackDetail;
    @BindView(R.id.idea_back_recycle)
    RecyclerView ideaBackRecycle;
    @BindView(R.id.idea_back_button)
    LinearLayout ideaBackButton;

    private IdeaBackRecycleAdapter adapter;
    private int REQUEST_CODE_CHOOSE = 1;
    private List<Uri> mSelected;
    private static final String FILE_PATH = "com.wgts.wgts.fileprovider";
    private String ideaBackImage;
    private List<IdeaBackRequest> imageList;
    private String adviceImages;

    @Inject
    IIdeaBackActivityPresenter presenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_center_idea_back_activity);
        ButterKnife.bind(this);
        includeTitle.setText("意见反馈");
        initView();
    }

    @Override
    public void init() {
        DaggerIdeaBackActivityComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .ideaBackActivityModule(new IdeaBackActivityModule(this))
                .build()
                .inject(this);
        imageList = new ArrayList<>();
    }

    private void initView(){
        mSelected = new ArrayList<>();
        ideaBackRecycle.setLayoutManager(new GridLayoutManager(IdeaBackActivity.this, 5,
                GridLayoutManager.VERTICAL, false));
        adapter = new IdeaBackRecycleAdapter(this, mSelected);
        ideaBackRecycle.setAdapter(adapter);
        adapter.setAddImageOnClick(new IdeaBackRecycleAdapter.addImageOnClick() {
            @Override
            public void addOnclick(View view, int position) {
                IdeaBackActivityPermissionsDispatcher.addIdeaBackImageWithPermissionCheck(IdeaBackActivity.this, 5 - mSelected.size());
            }
        });
        adapter.setDeleteImageOnClick(new IdeaBackRecycleAdapter.deleteImageOnClick() {
            @Override
            public void deleteOnclick(View view, int position) {
                mSelected.remove(position);
                adapter.setDate(mSelected);
            }
        });

    }

    @OnClick({R.id.back_btn_ly, R.id.idea_back_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn_ly:
                finish();
                break;
            case R.id.idea_back_button:
                upIdeaBack();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data ){
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            for (int i = 0; i < Matisse.obtainResult(data).size(); i++){
                mSelected.add(Matisse.obtainResult(data).get(i));
            }
            //mSelected = Matisse.obtainResult(data);
            adapter.setDate(mSelected);
        }
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void addIdeaBackImage(int size){
        Matisse.from(IdeaBackActivity.this)
                .choose(MimeType.ofAll(), false)
                .countable(true)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, FILE_PATH))
                .maxSelectable(size)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new com.wgts.wgts.control.matisse.GlideEngine()) // 使用的图片加载引擎
                .forResult(REQUEST_CODE_CHOOSE); // 设置作为标记的请求码
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void addIdeaBackImageWrong(){
        Toast.makeText(IdeaBackActivity.this,
                "获取权限失败，可能无法上传照片", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        IdeaBackActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    private void upIdeaBack(){
        if (ideaBackDetail.getText().toString().trim() == null || ideaBackDetail.getText().toString().trim().equals("")){
            MoHuToast.showToast("反馈意见不能为空");
            return;
        }
        uploadImage();
    }

    private void uploadImage(){
        imageList.clear();
        if (mSelected != null && mSelected.size() > 0){
            for (int i = 0; i < mSelected.size(); i++){
                final int finalI = i;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OssService.getInstance(IdeaBackActivity.this).beginupload("head",
                                FileUtils.getRealFilePath(IdeaBackActivity.this, mSelected.get(finalI)),
                                new OssService.ProgressCallback() {
                                    @Override
                                    public void onProgressCallback(double progress, String url) {
                                        if(progress == 100){
                                            ideaBackImage = url;
                                            if (ideaBackImage.equals("")){
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        MoHuToast.showToast("图片上传失败");
                                                        return;
                                                    }
                                                });
                                            }else {
                                                String filename = String.valueOf(System.currentTimeMillis()) + String.valueOf((int) ((Math.random() * 9 + 1) * 1000)) + "." + "png";
                                                IdeaBackRequest request = new IdeaBackRequest();
                                                request.filePath = url;
                                                request.fileName = filename;
                                                imageList.add(request);
                                                if (imageList.size() == mSelected.size()){
                                                    Gson gson = new Gson();
                                                    adviceImages = gson.toJson(imageList).toString();
                                                    //有图片的上传
                                                    presenter.upIdeaBack(emailAddress.getText().toString().trim(), ideaBackDetail.getText().toString().trim(),
                                                            adviceImages);
                                                }
                                            }
                                        }
                                    }
                                });
                    }
                }).start();
            }
        }else {
            //没有图片的上传
            adviceImages = "";
            showDialog();
            presenter.upIdeaBack(emailAddress.getText().toString().trim(), ideaBackDetail.getText().toString().trim(),
                    adviceImages);
        }
    }

    @Override
    public void onError(int status, String msg) {
        dialogDismiss();
        MoHuToast.showToast(msg);
    }

    @Override
    public void upIdeaBack(IdeaBackEntity entity) {
        dialogDismiss();
        MoHuToast.showToast("反馈成功");
        finish();
    }
}
